// src/composables/useResizeHandler.js
import { onMounted, onBeforeUnmount, onActivated, onDeactivated } from "vue";
import { debounce } from "@/utils";

export function useResizeHandler(getChartInstance) {
  let resizeHandler = null;
  let sidebarElm = null;

  const resize = () => {
    const chart = getChartInstance();
    console.log(chart);
    if (chart && chart.resize) {
      chart.resize();
    }
  };

  const sidebarResizeHandler = (e) => {
    if (e.propertyName === "width") {
      resizeHandler && resizeHandler();
    }
  };

  const initListener = () => {
    resizeHandler = debounce(() => {
      resize();
    }, 100);

    window.addEventListener("resize", resizeHandler);

    sidebarElm = document.getElementsByClassName("sidebar-container")[0];
    if (sidebarElm) {
      sidebarElm.addEventListener("transitionend", sidebarResizeHandler);
    }
  };

  const destroyListener = () => {
    if (resizeHandler) {
      window.removeEventListener("resize", resizeHandler);
      resizeHandler = null;
    }

    if (sidebarElm) {
      sidebarElm.removeEventListener("transitionend", sidebarResizeHandler);
      sidebarElm = null;
    }
  };

  onMounted(initListener);
  onActivated(() => {
    if (!resizeHandler) initListener();
    resize();
  });
  onDeactivated(destroyListener);
  onBeforeUnmount(destroyListener);
}
